package com.huike.clues.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huike.clues.domain.SysRole;
import com.huike.clues.domain.vo.SysRoleVO;
import com.huike.clues.mapper.SysRoleDeptMapper;
import com.huike.clues.mapper.SysRoleMenuMapper;
import com.huike.common.constant.DataScopeConstant;
import com.huike.common.constant.ScheduleConstants;
import com.huike.common.core.page.SystemParamsQuery;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.bean.BeanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huike.common.core.domain.entity.SysRoleDTO;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.spring.SpringUtils;
import com.huike.clues.mapper.SysRoleMapper;
import com.huike.clues.service.ISysRoleService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 角色 业务层处理
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final SysRoleMapper roleMapper;


    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRoleDTO> selectRoleAll() {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRoleDTO());
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRoleDTO> selectRoleList(SysRoleDTO role) {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Integer> selectRoleListByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRoleDTO> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRoleDTO perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }


    /**
     * 分页查询角色列表
     *
     * @return 返回查询结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page<List<SysRoleVO>> findAll(SystemParamsQuery queryPageBean) {

        PageHelper.startPage(queryPageBean.getPageNum(), queryPageBean.getPageSize());

        Map<String, Object> params = queryPageBean.getParams();
        String beginTime = (String) params.get("beginTime");
        String endTime = (String) params.get("endTime");

        Page<List<SysRoleVO>> page =
                roleMapper.findAll(queryPageBean.getRoleName() , queryPageBean.getRoleKey() ,
                beginTime , endTime , queryPageBean.getStatus());

        return page;
    }

    /**
     * 新增角色
     *
     * @param sysRoleDTO
     */
    @Override
    public void add(SysRoleDTO sysRoleDTO) {

        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDTO, sysRole);


        sysRole.setUpdateTime(LocalDateTime.now().toString());
        sysRole.setCreateBy(SecurityUtils.getUsername());
        sysRole.setCreateTime(LocalDateTime.now().toString());
        sysRole.setDataScope(DataScopeConstant.ONE);
        sysRole.setDeptCheckStrictly(1);
        sysRole.setMenuCheckStrictly(1);
        sysRole.setStatus(ScheduleConstants.MISFIRE_DEFAULT);
        sysRole.setUpdateBy(SecurityUtils.getUsername());


        roleMapper.insert(sysRole);
        Long roleId = sysRole.getRoleId();
        Long[] menuIds = sysRoleDTO.getMenuIds();
        for (Long menuId : menuIds) {
            sysRoleMenuMapper.add(roleId, menuId);
        }
    }

    private final SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public SysRoleVO findByRoleId(Long roleId) {
        SysRole sysRole = roleMapper.select(roleId);

        SysRoleVO sysRoleVO = new SysRoleVO();

        BeanUtils.copyProperties(sysRole, sysRoleVO);


        return sysRoleVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(SysRoleDTO sysRoleDTO) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDTO,sysRole);

        sysRole.setUpdateBy(SecurityUtils.getUsername());
        sysRole.setUpdateTime(LocalDateTime.now().toString());

        sysRoleMenuMapper.deleteRoleMenuByRoleId(sysRole.getRoleId());

        Long roleId = sysRole.getRoleId();
        Long[] menuIds = sysRoleDTO.getMenuIds();
        for (Long menuId : menuIds) {
            sysRoleMenuMapper.add(roleId, menuId);
        }

        sysRoleDeptMapper.deleteRoleDeptByRoleId(sysRole.getRoleId());

        for (Long menuId : menuIds) {
            sysRoleDeptMapper.add(roleId, menuId);
        }

        roleMapper.updateById(sysRole);
    }
private final SysRoleDeptMapper sysRoleDeptMapper;
    @Override
    public void changeStatus(SysRoleDTO sysRoleDTO) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDTO,sysRole);

        sysRole.setCreateBy(SecurityUtils.getUsername());

        sysRole.setCreateTime(LocalDateTime.now().toString());

        roleMapper.updateById(sysRole);
    }

    @Override
    public void daleteRole(List<Long> roleIds) {

        for (Long roleId : roleIds) {
            sysRoleMenuMapper.deleteRoleMenuByRoleId(roleId);
            sysRoleDeptMapper.deleteRoleDeptByRoleId(roleId);
        }
        roleMapper.deleteBatchIds(roleIds);

    }
}
